import { Canvas, useThree, useLoader } from '@react-three/fiber';
import {Html, OrbitControls} from '@react-three/drei';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

import {Suspense, useEffect, useRef, useState} from 'react';
import {useNavigate} from "react-router-dom";


function ModelFromBlob({ url }) {
  const gltf = useLoader(GLTFLoader, url);
  return <primitive object={gltf.scene} scale={0.5} />;
}

function useGLBWithProgress(url) {
  const [progress, setProgress] = useState(0);
  const [blobUrl, setBlobUrl] = useState(null);

  useEffect(() => {
    const fetchGLB = async () => {
      const res = await fetch(url);
      const reader = res.body.getReader();
      const length = +res.headers.get('Content-Length');
      let received = 0;
      const chunks = [];

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        chunks.push(value);
        received += value.length;
        setProgress((received / length) * 100);
      }

      const blob = new Blob(chunks);
      const objectURL = URL.createObjectURL(blob);
      setBlobUrl(objectURL);
    };

    fetchGLB();
  }, [url]);

  return { progress, blobUrl };
}


function CanvasSuspense() {
  return (
    <Html center={true}>
      <div
      style={{
        width: '1000px',
      }}>
        <h1>稍等几秒，正在渲染到画布中</h1>
        <div style={{
          color: '#989898',
          margin: '16px 0 0 0',
        }}>
          Made by ~ <b>伍余林翰</b> <a href={"mailto:2627205945@qq.com"}><b>2627205945@qq.com</b></a>
        </div>
      </div>
    </Html>
  )
}


function MyCanvas({position, target}) {
  const { progress, blobUrl } = useGLBWithProgress('/heritage/merge2.glb');

  if (!blobUrl) {
    return (
      <div style={{
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        padding: '20px 30px',
        background: '#000',
        color: '#fff',
        borderRadius: '12px',
      }}>
        <div>
          <h3>模型较大，请您稍等一下</h3>
        </div>
        ⏳ 加载中：{progress.toFixed(1)}%
        <div style={{
          color: '#989898',
          margin: '16px 0 0 0',
        }}>
          Made by ~ <b>伍余林翰</b> <a href={"mailto:2627205945@qq.com"}><b>2627205945@qq.com</b></a>
        </div>
      </div>
    );
  }

  return (
    <Canvas style={{position: 'fixed', top: 0, left: 0, width: '100%', height: '100%'}}>

      <Suspense fallback={<CanvasSuspense/>}>
        <ambientLight/>
        <pointLight position={[10, 10, 10]}/>

        <ModelFromBlob url={blobUrl}/>

        <InitCamera
          position={position}
          target={target}
        />
        <CameraLogger/>
      </Suspense>

    </Canvas>
  );
}


export default function ModelPage2() {

  // ✅ 多个场景预设
  const scenePresets = {
    scene4: {
      name: "程氏祠堂鸟瞰 1",
      position: [4.89, 10.90, -13.98],
      target: [25.86, -3.37, -18.66],
    },
    scene5: {
      name: "程氏祠堂鸟瞰 2",
      position: [20.58, 14.47, -12.37],
      target: [19.26, 0.05, -17.75],
    },
    scene6: {
      name: "程氏祠堂侧门",
      position: [16.70, 3.12, -9.15],
      target: [19.27, 1.33, -18.37],
    },
  };

  // ✅ 当前激活视角
  const [activeScene, setActiveScene] = useState('scene4');

  const [isHovered, setIsHovered] = useState(false);
  const navigate = useNavigate();

  return (
    <>

      <div
        style={{
          position: 'fixed',
          bottom: 20,
          left: 20,
          zIndex: 1000,
        }}
      >
        {/* 返回按钮 */}
        <button
          style={{
            padding: '6px 12px',
            background: '#333',
            color: '#fff',
            border: 'none',
            borderRadius: '6px',
            cursor: 'pointer',
            fontSize: '14px',
          }}
          onClick={() => navigate('/heritage/')}
        >
          返回详情页
        </button>
      </div>

      {/* ✅ 左侧 UI：场景列表 */}
      <div
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        style={{
          position: 'fixed',
          bottom: 10,
          left: '50%',
          transform: 'translateX(-50%)',           // ✅ 水平居中
          zIndex: 1000,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          background: 'rgba(16, 16, 16, 0.68)',
          backdropFilter: 'blur(10px)',
          WebkitBackdropFilter: 'blur(10px)',
          padding: '20px 20px',
          borderRadius: '12px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
          transition: 'all 0.3s ease',
          gap: '16px', // 每个按钮之间更舒服的间距
        }}
      >
        {/* 场景按钮列表 */}
        <div style={{display: 'flex', gap: '12px', alignItems: 'center'}}>
          {Object.keys(scenePresets).map((key) => (
            <button
              key={key}
              onClick={() => setActiveScene(key)}
              style={{
                width: isHovered ? '200px' : '200px',
                height: isHovered ? '160px' : '36px',
                padding: isHovered ? 0 : '6px 12px',
                background: activeScene === key ? '#0aa' : '#eee',
                color: activeScene === key ? '#fff' : '#333',
                border: 'none',
                borderRadius: '8px',
                cursor: 'pointer',
                overflow: 'hidden',
                transition: 'all 0.3s ease-in-out',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              {isHovered ? (
                <img
                  src={`/heritage/thumbnails/${key}.png`}
                  alt={key}
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                    display: 'block',
                  }}
                />
              ) : (
                scenePresets[key].name
              )}
            </button>
          ))}
        </div>
      </div>

      <MyCanvas
        position={scenePresets[activeScene].position}
        target={scenePresets[activeScene].target}
      />

    </>
  );
}

function InitCamera({position, target = [0, 0, 0]}) {
  const {camera, scene} = useThree();
  const controlsRef = useRef();

  useEffect(() => {
    camera.position.fromArray(position);
    controlsRef.current.target.fromArray(target);
    controlsRef.current.update();
    camera.updateProjectionMatrix();

    // ✅ 把 controls 挂到 scene 上，方便 Logger 访问
    scene.userData.controls = controlsRef.current;
  }, [position, target]);

  return <OrbitControls ref={controlsRef}/>;
}

function CameraLogger() {
  const {camera, scene} = useThree();
  const intervalRef = useRef(null);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      const position = camera.position.toArray();
      const quaternion = camera.quaternion.toArray();

      const controls = scene.userData.controls;
      const target = controls ? controls.target.toArray() : ['N/A'];

      console.log('📸 摄像机位置:', position);
      console.log('📐 摄像机四元:', quaternion);
      console.log('🎯 观察目标点:', target);
    }, 1000);

    return () => clearInterval(intervalRef.current);
  }, []);

  return null;
}
